﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System
{
    public static class ObjectMap
    {
        //反射实现一个对象字段Map方法
        public static T Map<T>(this object source)
        {
            T target = Activator.CreateInstance<T>();
            var sourceProperties = source.GetType().GetProperties();
            var targetProperties = target.GetType().GetProperties();
            foreach (var sourceProperty in sourceProperties)
            {
                var targetProperty = targetProperties.FirstOrDefault(p => p.Name == sourceProperty.Name);
                if (targetProperty != null)
                {
                    targetProperty.SetValue(target, sourceProperty.GetValue(source));
                }
            }
            return target;
        }
    }
}
